<?php

namespace app\admin\service;

use app\admin\model\AdminModel;
use app\admin\model\LoginLogModel;
use app\admin\model\RoleModel;
use app\admin\validate\AdminValidate;
use app\common\libs\helper\StringHelper;
use app\common\libs\helper\TreeHelper;
use Exception;
use think\Exception as ThinkException;
use think\exception\ValidateException;
use think\facade\Cookie;

class AdminService extends BaseService
{
    protected static $hander;

    /**
    * 单例模式
    *
    * @Author tanruizheng
    * @DateTime 2021-07-09
    * @return object
    */
    public static function instance(){
        if(!self::$hander){
            self::$hander = new AdminService;
        }
        return self::$hander;
    }

    /**
     * 管理员登陆
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @param [type] $username
     * @param [type] $password
     * @return void
     */
    public function doLogin($username, $password, $keeptime = 0){
        try {
            $loginTime = time();//当前登录时间
            $loginIp = request()->ip();//当前登录IP
            //判断用户名是否正确
            $adminInfo = AdminModel::where('username',$username)->find();
            if(!$adminInfo){
                //创建登陆日志
                LoginLogModel::createLoginLog($username,$password,$loginTime,$loginIp,0,$password);
                return self::createFail('用户名或者密码错误');
            }
            //判断密码是否正确
            if(md5($password.md5($adminInfo['verify'])) !== $adminInfo['password']){
                //创建登陆日志
                LoginLogModel::createLoginLog($username,$password,$loginTime,$loginIp,0,$password);
                return self::createFail('用户名或者密码错误');
            }
            //记录最后登录时间和ip
            $adminInfo->save(['last_login_time' => $loginTime,'last_login_ip' => $loginIp]);
            //记录登陆信息
            session('adminInfo',$adminInfo);//管理员信息
            session('adminId',$adminInfo['id']);//管理员ID
            //创建登陆日志
            LoginLogModel::createLoginLog($username,$password,$loginTime,$loginIp,1);
            //记住登录
            self::keeplogin($keeptime, $adminInfo);
            return self::createSuccess('登陆成功',$adminInfo);
        } catch (\Exception $e) {
            return self::createFail($e->getMessage());
        }
    }

    /**
     * 刷新保持登录的Cookie
     *
     * @Author tanruizheng
     * @DateTime 2021-07-28
     * @param integer $keeptime
     * @return void
     */
    public static function keeplogin($keeptime = 0, $adminInfo = [])
    {
        if ($keeptime) {
            $data = [$adminInfo['id'], $keeptime];
            Cookie::set('keeplogin', implode('|', $data), $keeptime);
            return true;
        }
        return false;
    }

    /**
     * 自动登录
     * @return boolean
     */
    public static function autologin()
    {
        $keeplogin = Cookie::get('keeplogin');
        if (!$keeplogin) {
            return false;
        }
        list($id, $keeptime) = explode('|', $keeplogin);
        if ($id && $keeptime) {
            $adminInfo = AdminModel::findOrEmpty($id)->toArray();
            if (!$adminInfo) {
                return false;
            }
            $ip = request()->ip();
            //IP有变动
            if ($adminInfo['last_login_ip'] != $ip) {
                return false;
            }
            //记录登陆信息
            session('adminInfo',$adminInfo);//管理员信息
            session('adminId',$adminInfo['id']);//管理员ID
            //刷新自动登录的时效
            self::keeplogin($keeptime, $adminInfo);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取登陆的管理员信息
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @return array
     */
    public function getAdminInfo(){
        $adminInfo = session('adminInfo');//登陆的用户信息
        $adminInfo = AdminModel::where('id',$adminInfo['id'])->find()->toArray();
        return $adminInfo ?: [];
    }

    /**
     * 判断是否登陆
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @return boolean
     */
    public function isLogin(){
        $adminId = session('adminId');
        return $adminId ?? false;
    }

     /**
     * 获取管理员列表
     *
     * @Author tanruizheng
     * @DateTime 2021-07-12
     * @param array $where
     * @return void
     */
    public static function getAdminList($params = [], $page = 1, $limit = 15){
        $where = [];
        //启用状态
        if(isset($params['status']) && $params['status'] !== ''){
            $where[] = ['status','=',$params['status']];
        }
        //用户名
        if(isset($params['username']) && $params['username'] !== ''){
            $where[] = ['username','=',$params['username']];
        }
        //昵称
        if(isset($params['nickname']) && $params['nickname'] !== ''){
            $where[] = ['nickname','like','%'.$params['nickname'].'%'];
        }
        //角色ID
        if(empty($params['role_id'])){
            $roleList = RoleModel::where([])->select()->toArray();
            $adminInfo = AdminService::instance()->getAdminInfo();
            if($adminInfo['role_id'] == AdminModel::SUPER_ADMIN_ROLE_ID){
                //超级管理员

            }else{
                $sonRoleList = TreeHelper::getSonNodeFromArray($roleList,$adminInfo['role_id'],[
                    'parentKey' => 'parentid'
                ]);
                $sonRoleList = $sonRoleList ?? [0];
                $roleIds = array_map(function($item){
                    return $item['id'];
                },$sonRoleList);
                $where[] = ['role_id','in',$roleIds];
            }
        }else{
            $where[] = ['role_id','=',$params['role_id']];
        }
        //管理员列表
        $adminList = AdminModel::where($where)->page($page,$limit)->select()->toArray();
        foreach ($adminList as &$value) {
            $value['role_name'] = RoleModel::where('id',$value['role_id'])->value('name');
            //最后登录时间
            if($value['last_login_time']){
                $value['last_login_time'] = date('Y-m-d H:i:s',$value['last_login_time']);
            }
        }
        //管理员总数
        $count = AdminModel::where($where)->count();
        return self::createList($adminList,$count);
    }

    /**
     * 添加或者编辑管理员
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @param [type] $params
     * @return void
     */
    public static function addOrEditData($params){
        try {
            validate(AdminValidate::class)->check($params);
            $data = [];
            isset($params['username']) && $data['username'] = $params['username'];
            isset($params['email']) && $data['email'] = $params['email'];
            isset($params['status']) && $data['status'] = $params['status'];
            isset($params['remark']) && $data['remark'] = $params['remark'];
            isset($params['role_id']) && $data['role_id'] = $params['role_id'];
            isset($params['nickname']) && $data['nickname'] = $params['nickname'];

            //密码
            if(isset($params['password']) && $params['password']){
                $verify = StringHelper::genRandomString(6);
                $data['verify'] = $verify;
                $data['password'] = md5($params['password'].md5($verify));
            }   
            if($data['username']){
                $checkUsername = AdminModel::where('username',$data['username'])->find();
            }

            if($data['email']){
                $checkEmail = AdminModel::where('email',$data['email'])->find();
            }
           
            if(isset($params['id']) && $params['id']){
                //判断用户名是否存在
                if($checkUsername && $checkUsername['id'] != $params['id']){
                    return self::createFail('用户名已经存在!');
                }
                //判断邮箱是否存在
                if($checkEmail && $checkEmail['id'] != $params['id']){
                    return self::createFail('邮箱已经存在!');
                }
                $res = AdminModel::where('id',$params['id'])->save($data);
            }else{
                //判断用户名是否存在
                if($checkUsername){
                    return self::createFail('用户名已经存在!');
                }
                //判断邮箱是否存在
                if($checkEmail){
                    return self::createFail('邮箱已经存在!');
                }
                $res = AdminModel::create($data);
            }
            if($res !== false){
                return self::createSuccess('保存成功');
            }
            return self::createFail('保存失败');
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::createFail($e->getError());
        }
    }

    /**
     * 获取管理员详情
     *
     * @Author tanruizheng
     * @DateTime 2021-07-13
     * @param [type] $roleId
     * @return void
     */
    public static function getAdminDetail($adminId){
        $data = AdminModel::where('id',$adminId)->findOrEmpty();
        return $data;
    }

    /**
     * 管理员删除
     *
     * @Author tanruizheng
     * @DateTime 2021-07-13
     * @param [type] $adminId
     * @return void
     */
    public static function adminDelete($adminId){
        if(!$adminId){
            return self::createFail('参数错误!');
        }
        $adminDetail = self::getAdminDetail($adminId);
        if(!$adminDetail){
            return self::createFail('管理员不存在!');
        }
        if($adminDetail['role_id'] == AdminModel::SUPER_ADMIN_ROLE_ID){
            return self::createFail('超级管理员不能删除!');
        }
        $result = $adminDetail->delete();
        if($result !== false){
            return self::createSuccess('删除成功');
        }
        return self::createSuccess('删除失败');
    }

    /**
     * 更新基本信息
     *
     * @Author tanruizheng
     * @DateTime 2021-07-15
     * @param [type] $params
     * @return void
     */
    public static function updateBasicInfo($params){
        try {
            $data = [
                'nickname' => $params['nickname'],
                'email' => $params['email'],
                'remark' => $params['remark'],
            ];

            if($data['email']){
                $checkEmail = AdminModel::where('email',$data['email'])->find();
            }
            //判断邮箱是否存在
            if($checkEmail && $checkEmail['id'] != $params['id']){
                return self::createFail('邮箱已经存在!');
            }
            $res = AdminModel::where('id',$params['id'])->save($data);
            if($res !== false){
                return self::createSuccess('保存成功');
            }
            return self::createFail('保存失败');
        } catch (ThinkException $e) {
            // 验证失败 输出错误信息
            return self::createFail($e->getMessage());
        }
    }

    /**
     * 修改密码
     *
     * @Author tanruizheng
     * @DateTime 2021-07-15
     * @param [type] $params
     * @return void
     */
    public static function changePassword($params){
        try {
            if(!$params['old_password']){
                return self::createFail('旧密码不能为空!');
            }
            if(!$params['new_password']){
                return self::createFail('新的密码不能为空!');
            }
            if(!$params['again_password']){
                return self::createFail('新的密码不能为空!');
            }
            $adminInfo = self::instance()->getAdminInfo();
            //旧密码判断
            if($adminInfo['password'] != md5($params['old_password'].md5($adminInfo['verify']))){
                return self::createFail('旧密码错误!');
            }
            //确认密码比较
            if($params['new_password'] != $params['again_password']){
                return self::createFail('新密码不一致!');
            }
            $verify = StringHelper::genRandomString(6);
            $data['verify'] = $verify;
            $data['password'] = md5($params['new_password'].md5($verify));
            $res = AdminModel::where('id',$adminInfo['id'])->save($data);
            if($res !== false){
                return self::createSuccess('保存成功');
            }
            return self::createFail('保存失败');
        } catch (ThinkException $e) {
            // 验证失败 输出错误信息
            return self::createFail($e->getMessage());
        }
    }
}